package com.cyy.controller

import com.cyy.util.execute
import com.cyy.view.Sett
import com.cyy.view.Setts
import com.cyy.view.toSett
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
import org.jetbrains.exposed.sql.SqlExpressionBuilder.like
import tornadofx.*
import java.sql.DriverManager

object SettEventModel {
    class AddRequest(val kkey: String = "", val vvalue: String = "") : FXEvent(EventBus.RunOn.BackgroundThread)
    class AddEvent(val item: Sett) : FXEvent()

    class FilterByNameRequest(val nameLike: String = "") : FXEvent(EventBus.RunOn.BackgroundThread)
    class FilterByNameEvent(val items: List<Sett>?) : FXEvent()

    class UpdateRequest(val item: Sett) : FXEvent(EventBus.RunOn.BackgroundThread)
    class UpdateEvent(val id: Int) : FXEvent()

    class FavoritesChangedEvent(val items: List<Sett>) : FXEvent()

    class DeleteRequest(val id: Int) : FXEvent(EventBus.RunOn.BackgroundThread)
    class DeleteEvent(val id: Int) : FXEvent()

    class RefreshRequest : FXEvent(EventBus.RunOn.BackgroundThread)
    class RefreshEvent(val items: List<Sett>) : FXEvent()
}

class SettController : Controller() {

    init {
        subscribe<SettEventModel.AddRequest> {
            fire(SettEventModel.AddEvent(add(it.kkey, it.vvalue)))
        }
        subscribe<SettEventModel.UpdateRequest> {
            fire(SettEventModel.UpdateEvent(update(it.item)))
        }
        subscribe<SettEventModel.DeleteRequest> {
            fire(SettEventModel.DeleteEvent(delete(it.id)))
        }
        subscribe<SettEventModel.RefreshRequest> {
            fire(SettEventModel.RefreshEvent(getAll()))
        }
        subscribe<SettEventModel.FilterByNameRequest> {
            fire(SettEventModel.FilterByNameEvent(filterByName(it.nameLike)))
        }
    }

    private fun add(newkkey: String, newvvalue: String): Sett {
        val newSett = execute {
            Setts.insert {
                it[kkey] = newkkey
                it[vvalue] = newvvalue
            }
        }
        return Sett(newSett[Setts.id], newkkey, newvvalue)
    }

    private fun update(item: Sett): Int {
        val id = execute {
            Setts.update({ Setts.id eq item.id }) {
                it[kkey] = item.kkey
                it[vvalue] = item.vvalue
            }
        }
        fire(SettEventModel.FavoritesChangedEvent(getAll()))
        return id
    }

    private fun delete(id: Int) = execute {
        Setts.deleteWhere { Setts.id eq id }
    }

    private fun getAll(): List<Sett> = execute {
        Setts.selectAll().map { it.toSett() }
    }

    private fun filterByName(kkey: String): List<Sett> = execute {
        Setts.select { Setts.kkey like "%$kkey%" }.map { it.toSett() }
    }
}

fun main(){
    val (a,b)=p()
    println(a)
    println(b)

}
fun p():Pair<Int,Int> = Pair(1,2)